#include <iostream>
#include <sstream>
#include <iomanip>
#include <chrono>
#include "execution/execution_types.h"
#include "execution/order_manager.h"

namespace hft {

OrderManager::OrderManager() {
}

std::string OrderManager::createOrder(const Order& order) {
    // 生成订单ID
    std::string order_id = generateOrderId();
    
    // 创建新订单
    Order new_order = order;
    new_order.order_id = order_id;
    new_order.status = OrderStatus::Created;
    new_order.create_time = std::chrono::system_clock::now();
    new_order.update_time = new_order.create_time;
    
    // 添加到订单映射表
    orders_[order_id] = new_order;
    
    // 通知订单状态更新
    notifyOrderUpdate(new_order);
    
    return order_id;
}

bool OrderManager::modifyOrder(const std::string& order_id, double price, int volume) {
    auto it = orders_.find(order_id);
    if (it == orders_.end()) {
        return false;
    }
    
    Order& order = it->second;
    
    // 检查订单是否可以修改
    if (order.status != OrderStatus::Created && 
        order.status != OrderStatus::Pending && 
        order.status != OrderStatus::PartialFilled) {
        return false;
    }
    
    // 修改订单
    if (price > 0) {
        order.price = price;
    }
    
    if (volume > 0) {
        order.volume = volume;
    }
    
    order.update_time = std::chrono::system_clock::now();
    
    // 通知订单状态更新
    notifyOrderUpdate(order);
    
    return true;
}

bool OrderManager::cancelOrder(const std::string& order_id) {
    auto it = orders_.find(order_id);
    if (it == orders_.end()) {
        return false;
    }
    
    Order& order = it->second;
    
    // 检查订单是否可以取消
    if (order.status != OrderStatus::Created && 
        order.status != OrderStatus::Pending && 
        order.status != OrderStatus::PartialFilled) {
        return false;
    }
    
    // 取消订单
    order.status = OrderStatus::Canceled;
    order.update_time = std::chrono::system_clock::now();
    
    // 通知订单状态更新
    notifyOrderUpdate(order);
    
    return true;
}

int OrderManager::cancelOrders(const std::vector<std::string>& order_ids) {
    int canceled_count = 0;
    for (const auto& order_id : order_ids) {
        if (cancelOrder(order_id)) {
            canceled_count++;
        }
    }
    return canceled_count;
}

int OrderManager::cancelAllOrders() {
    int canceled_count = 0;
    for (auto& [order_id, order] : orders_) {
        if (order.status == OrderStatus::Created || 
            order.status == OrderStatus::Pending || 
            order.status == OrderStatus::PartialFilled) {
            order.status = OrderStatus::Canceled;
            order.update_time = std::chrono::system_clock::now();
            notifyOrderUpdate(order);
            canceled_count++;
        }
    }
    return canceled_count;
}

int OrderManager::cancelSymbolOrders(const std::string& symbol) {
    int canceled_count = 0;
    for (auto& [order_id, order] : orders_) {
        if (order.symbol == symbol && 
            (order.status == OrderStatus::Created || 
             order.status == OrderStatus::Pending || 
             order.status == OrderStatus::PartialFilled)) {
            order.status = OrderStatus::Canceled;
            order.update_time = std::chrono::system_clock::now();
            notifyOrderUpdate(order);
            canceled_count++;
        }
    }
    return canceled_count;
}

int OrderManager::cancelAccountOrders(const std::string& account) {
    int canceled_count = 0;
    for (auto& [order_id, order] : orders_) {
        if (order.account == account && 
            (order.status == OrderStatus::Created || 
             order.status == OrderStatus::Pending || 
             order.status == OrderStatus::PartialFilled)) {
            order.status = OrderStatus::Canceled;
            order.update_time = std::chrono::system_clock::now();
            notifyOrderUpdate(order);
            canceled_count++;
        }
    }
    return canceled_count;
}

int OrderManager::cancelStrategyOrders(const std::string& strategy_id) {
    int canceled_count = 0;
    for (auto& [order_id, order] : orders_) {
        if (order.strategy_id == strategy_id && 
            (order.status == OrderStatus::Created || 
             order.status == OrderStatus::Pending || 
             order.status == OrderStatus::PartialFilled)) {
            order.status = OrderStatus::Canceled;
            order.update_time = std::chrono::system_clock::now();
            notifyOrderUpdate(order);
            canceled_count++;
        }
    }
    return canceled_count;
}

void OrderManager::onOrderStatus(const Order& order) {
    auto it = orders_.find(order.order_id);
    if (it == orders_.end()) {
        // 如果订单不存在，添加到订单映射表
        orders_[order.order_id] = order;
    } else {
        // 更新订单状态
        Order& existing_order = it->second;
        existing_order.status = order.status;
        existing_order.filled_volume = order.filled_volume;
        existing_order.avg_fill_price = order.avg_fill_price;
        existing_order.update_time = std::chrono::system_clock::now();
    }
    
    // 通知订单状态更新
    notifyOrderUpdate(orders_[order.order_id]);
}

void OrderManager::onTrade(const Trade& trade) {
    // 添加到成交映射表
    trades_[trade.trade_id] = trade;
    
    // 更新订单状态
    auto it = orders_.find(trade.order_id);
    if (it != orders_.end()) {
        Order& order = it->second;
        
        // 更新成交数量和平均成交价格
        int new_filled_volume = order.filled_volume + trade.volume;
        double new_avg_fill_price = (order.filled_volume * order.avg_fill_price + trade.volume * trade.price) / new_filled_volume;
        
        order.filled_volume = new_filled_volume;
        order.avg_fill_price = new_avg_fill_price;
        
        // 更新订单状态
        if (order.filled_volume >= order.volume) {
            order.status = OrderStatus::Filled;
        } else if (order.filled_volume > 0) {
            order.status = OrderStatus::PartialFilled;
        }
        
        order.update_time = std::chrono::system_clock::now();
        
        // 通知订单状态更新
        notifyOrderUpdate(order);
    }
    
    // 通知成交回报
    notifyTrade(trade);
}

Order* OrderManager::getOrder(const std::string& order_id) {
    auto it = orders_.find(order_id);
    if (it != orders_.end()) {
        return &it->second;
    }
    return nullptr;
}

std::vector<Order*> OrderManager::getAccountOrders(const std::string& account) {
    std::vector<Order*> result;
    for (auto& [order_id, order] : orders_) {
        if (order.account == account) {
            result.push_back(&order);
        }
    }
    return result;
}

std::vector<Order*> OrderManager::getStrategyOrders(const std::string& strategy_id) {
    std::vector<Order*> result;
    for (auto& [order_id, order] : orders_) {
        if (order.strategy_id == strategy_id) {
            result.push_back(&order);
        }
    }
    return result;
}

std::vector<Order*> OrderManager::getSymbolOrders(const std::string& symbol) {
    std::vector<Order*> result;
    for (auto& [order_id, order] : orders_) {
        if (order.symbol == symbol) {
            result.push_back(&order);
        }
    }
    return result;
}

const std::unordered_map<std::string, Order>& OrderManager::getAllOrders() const {
    return orders_;
}

std::vector<Order*> OrderManager::getActiveOrders() {
    std::vector<Order*> result;
    for (auto& [order_id, order] : orders_) {
        if (order.status == OrderStatus::Created || 
            order.status == OrderStatus::Pending || 
            order.status == OrderStatus::PartialFilled) {
            result.push_back(&order);
        }
    }
    return result;
}

void OrderManager::cleanCompletedOrders() {
    std::vector<std::string> to_remove;
    for (const auto& [order_id, order] : orders_) {
        if (order.status == OrderStatus::Filled || 
            order.status == OrderStatus::Canceled || 
            order.status == OrderStatus::Rejected) {
            to_remove.push_back(order_id);
        }
    }
    
    for (const auto& order_id : to_remove) {
        orders_.erase(order_id);
    }
}

void OrderManager::registerOrderCallback(std::function<void(const Order&)> callback) {
    order_callback_ = callback;
}

void OrderManager::registerTradeCallback(std::function<void(const Trade&)> callback) {
    trade_callback_ = callback;
}

std::string OrderManager::generateOrderId() {
    // 生成订单ID，格式：yyyyMMddHHmmss-counter
    auto now = std::chrono::system_clock::now();
    auto now_time_t = std::chrono::system_clock::to_time_t(now);
    std::tm now_tm;
    localtime_s(&now_tm, &now_time_t);
    
    std::stringstream ss;
    ss << std::put_time(&now_tm, "%Y%m%d%H%M%S") << "-" << ++order_id_counter_;
    
    return ss.str();
}

void OrderManager::notifyOrderUpdate(const Order& order) {
    if (order_callback_) {
        order_callback_(order);
    }
}

void OrderManager::notifyTrade(const Trade& trade) {
    if (trade_callback_) {
        trade_callback_(trade);
    }
}

} // namespace hft